// pages/event/event_report/event_report.js
let app = getApp();
let domain = app.globalData.url;
//麦克风帧动画
function speaking() {
  //话筒帧动画
  let i = 1;
  this.timer = setInterval(()=> {
    i++;
    i = i % 5;
    this.setData({
      j: i
    })
  }, 200);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    areaCode: '',
    subclassId: '', //所属小类id，由上级页面地址参数可得 test?id=xx
    addr: '', // 区域地址 街道-社区-网格
    address: "",
    imageList: [], // 上传图片地址列表
    playing: false, // 是否正在播放
    isRecord: false, // 是否已录音
    isSpeaking: false, // 是否在播放
    j: 1, // 录音图片层，及时刷新，帧的原理
    radioPath: '', // 录音存放地址
    showTopTips: false, // 顶部错误信息，如果有，则会在顶部显示
    reporting: false, // 是否处于正在上报中，用于防止用户多次点击
    levelIndex: 0,
    bEventTypeNameArr: ['请选择'],
    bEventTypeArr: [''],
    bEventTypeIndx: 0,
    sEventTypeNameArr: ['请选择'],
    sEventTypeArr: [''],
    sEventTypeIndx: 0,
    areaIndex: [0, 0, 0],
    showAreaChoose: false, // 展示区域连级选择
    locationPermission: true,
    recordPermission: false,
    isPlay: false,
    isStop: false,
    isFirstAuth: true,
    touchTips: "按住说话",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 设置上传事件所属小类，跳转至本页面，路由上参数
    this.setData({
      theme: app.globalData.theme,
      subclassId: options.subclassId,
      areaCode: app.globalData.areaCode
    });
    wx.getSetting({
      success: res => {
        this.setData({
          isFirstAuth: res.authSetting['scope.record'] ? false : true
        });
      },
      fail: err => {
      }
    })
    // 调用微信定位功能 根据坐标查询详细地址。
    this.getCurrentLocationByServer();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //全局录音管理
    this.recorderManager = wx.getRecorderManager();
    this.innerAudioContext = wx.createInnerAudioContext();
    this.recorderManager.onStart((errMsg) => {
      if (this.data.isFirstAuth) {
        wx.stopRecord()
        this.setData({
          recordPermission: false,
          isSpeaking: false,
        });
      } else {
        this.setData({
          recordPermission: false,
          touchTips: "松开结束",
          isSpeaking: true
        });
      }
    })
    this.recorderManager.onError((errMsg) => {
      console.error(errMsg)
      // this.setData({
      //   recordPermission: true
      // });
    })
    this.recorderManager.onStop((res) => {
      if (this.data.isFirstAuth) {
        this.setData({
          radioPath: "",
          isRecord: false,
          isSpeaking: false,
          isFirstAuth: false,
        });
      } else {
        wx.showToast({
          title: '录音成功',
          icon: 'success',
          duration: 1000
        })
        this.setData({
          radioPath: res.tempFilePath,
          isRecord: true,
          isSpeaking: false,
          touchTips: "按住说话"
        })
      }
    });
    this.innerAudioContext.onEnded(() => {
      this.setData({
        isPlay: false
      });
    });
    this.innerAudioContext.onError((err) => {
      console.error(err);
      this.setData({
        isPlay: false
      });
      app.alert("温馨提示", "播放错误！")
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.innerAudioContext.destroy();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  changeAddress: function(e) {
    this.setData({
      address: e.detail.value,
    });
  },
  /** 
   * 根据微信定位坐标，通过服务器查询上报地 祥址 
   */
  getCurrentLocationByServer: function() {
    wx.showLoading({
      title: '定位中...',
    })
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: res=> {
        wx.hideLoading();
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          locationPermission: false
        });

        app.wxPostRequest("/applet/selectArea", {
          latitude: res.latitude,
          longitude: res.longitude
        }).then(result => {
          this.setData({
            address: result.data.address,
          });
        });
      },
      fail: function() {
        wx.hideLoading();
        this.setData({
          locationPermission: true
        });
      },
    })
  },
  /**
   * 重新打开定位权限
   */
  locationSetting: function(e) {
    if (!e.detail.authSetting["scope.userLocation"]) {
      this.setData({
        locationPermission: true
      });
    } else {
      this.setData({
        locationPermission: false
      });
      this.getCurrentLocationByServer();
    }
  },
  /**
   * 重新打开录音权限
   */
  recordSetting: function(e) {
    if (!e.detail.authSetting["scope.record"]) {
      this.setData({
        recordPermission: true
      });
    } else {
      this.setData({
        recordPermission: false,
        isFirstAuth: false
      });
    }
  },
  /**
   * 设置事件描述 输入框中的值
   */
  getTextareaValue: function(e) {
    this.setData({
      "textareaValue": e.detail.value
    });
  },
  /**
   *  提交 按钮点击事件
   */
  submit: function(e) {
    let checkInputData = this.validateData();
    if (checkInputData) {
      this.report();
    }
  },

  /**
   * 跳转至上报成功页面
   */
  success: function() {
    wx.showToast({
      title: '上报成功!',
    })
    wx.redirectTo({
      url: '/pages/event/event_record/event_record',
    })
  },
  /**
   * 跳转至上报失败页面
   */
  fail: function(errorMsg) {
    app.alert("警告", errorMsg)
  },
  /**
   * 请求服务器，上报事件
   */
  report: function() {
    app.confirm('提示', '确认上报吗?').then(result => {
      this.setData({
        reporting: true
      });
      wx.showLoading({
        title: '上报中...',
      })
      app.wxPostRequest("/watch/instaShot", {
        // peopleId: app.globalData.userInfo["people_id"],
        unit_uode: app.globalData.unitCode,
        unit_id:"ff8080816b02ce0f016b07b310e93bb4",
        detail: this.data.textareaValue,
        location: this.data.address,
        coordination: this.data.longitude + "," + this.data.latitude,
        event_type_id: "ff8080816f6a5c8f016f7a0af56f5d86",
        user_id:app.globalData.userInfo["user_id"],
        user_name:app.globalData.userInfo["name"],
        sex:app.globalData.userInfo["sex"]?1:0
      }).then(result => {
        if (result.data.code == 1) {
          let eventId = result.data.eventId;
          this.uploadEventFiles(eventId);
        } else {
          this.fail(result.data.msg);
        }
        this.setData({
          reporting: false
        });
      });
    });

  },
  /**
   * 上传事件附件
   */
  uploadEventFiles: function(eventId) {
    // 上传图片
    let imageList = this.data.imageList;
    for (let i = 0; i < imageList.length; i++) {
      wx.uploadFile({
        url: domain + '/addEventFilewx?event_id=' + eventId + '&userId=' + app.globalData.userInfo["user_id"] + '&type=image',
        filePath: imageList[i],
        name: 'image',
        fail: ()=> {
          app.alert("温馨提示","图片上传失败");
        }
      })
    }
    /*上传录音*/
    if (this.data.radioPath) {
      console.error("开始上传语音。" + this.data.radioPath);
      wx.uploadFile({
        url: domain + '/addEventFilewx?event_id=' + eventId + '&userId=' + app.globalData.userInfo["user_id"] + '&type=radio',
        filePath: this.data.radioPath,
        name: 'radio',
        fail: ()=> {
          app.alert("温馨提示", "录音上传失败");
        }
      })
    }
    this.success();
  },
  /* 选择图片 */
  chooseImage: function() {
    wx.chooseImage({
      sourceType: ['camera', 'album'],
      sizeType: ['compressed'],
      count: 8,
      success: res=> {
        let imageList = this.data.imageList;
        imageList = imageList.concat(res.tempFilePaths);
        if (imageList.length > 8) {
          this.setData({
            showTopTips: "最多上传8张图片。",
          })
          return false;
        }
        this.setData({
          imageList: imageList,
        })
      }
    })
  },
  /** 验证数据结构是否合理 */
  validateData: function() {
    if (!this.data.address) {
      this.setData({
        error: "请点击重新定位获取位置"
      })
      return false;
    }
    if (!this.data.textareaValue) {
      this.setData({
        error: "请输入事件描述"
      })
      return false;
    }
    return true;
  },

  /**
   * 用户点击事件触发，微信原生地图选择页面
   * 根据微信定位，查询出详细地址，以及坐标
   */
  getCurrentLocation: function() {
    wx.chooseLocation({
      success: res=> {
        this.setData({
          address: res.address,
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
    })
  },

  /**
   * 图片放大，预览
   */
  previewImage: function(e) {
    let current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.imageList,
    })
  },

  /**
   * 录音部分
   */
  //手指按下,开始录音
  touchdown: function() {
    const options = {
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    // 开始录音
    this.recorderManager.start(options);
    // 调用录音层，友好提示，录音中
    speaking.call(this);
    if (this.data.recordPermission) {
      this.setData({
        isSpeaking: true
      });
    }
  },
  // 手指抬起,停止录音
  touchup: function() {
    this.recorderManager.stop();
  },
  // 点击播放录音
  playVoice: function (e) {
    this.setData({
      isPlay: true
    });
    this.innerAudioContext.src = this.data.radioPath;
    this.innerAudioContext.play();
  },
  //暂停录音
  pauseVoice: function () {
    this.setData({
      isStop: true
    });
    this.innerAudioContext.pause();
  },
  //停止播放
  stopVoice: function () {
    this.setData({
      isPlay: false
    });
    this.innerAudioContext.stop();
  },
  //删除语音
  deleteVoice: function () {
    this.innerAudioContext.stop();
    app.alert("是否删除？", "删除后可重新录制！").then(() => {
      this.setData({
        isRecord: false,
        radioPath: ""
      })
    });
  },
})